import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AIModel, ModelComparison } from '@/types/model';
import { createAsyncThunk } from '@reduxjs/toolkit';
import { getModels, getModelComparisons } from '@/api/modelApi';

interface ModelState {
  models: AIModel[];
  currentModel: string;
  comparisons: ModelComparison[];
  loading: boolean;
  error: string | null;
}

const initialState: ModelState = {
  models: [],
  currentModel: '',
  comparisons: [],
  loading: false,
  error: null
};

const modelSlice = createSlice({
  name: 'models',
  initialState,
  reducers: {
    fetchModelsStart: (state) => {
      state.loading = true;
      state.error = null;
    },
    fetchModelsSuccess: (state, action: PayloadAction<AIModel[]>) => {
      state.loading = false;
      state.models = action.payload;
      if (action.payload.length > 0) {
        state.currentModel = action.payload.find(m => m.isDefault)?.id || action.payload[0].id;
      }
    },
    fetchModelsFailure: (state, action: PayloadAction<string>) => {
      state.loading = false;
      state.error = action.payload;
    },
    fetchModelComparisonsSuccess: (state, action: PayloadAction<ModelComparison[]>) => {
      state.comparisons = action.payload;
    },
    setCurrentModel: (state, action: PayloadAction<string>) => {
      state.currentModel = action.payload;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchModels.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchModels.fulfilled, (state, action: PayloadAction<AIModel[]>) => {
        state.loading = false;
        state.models = action.payload;
        if (action.payload.length > 0) {
          state.currentModel = action.payload.find(m => m.isDefault)?.id || action.payload[0].id;
        }
      })
      .addCase(fetchModels.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取模型列表失败';
      });
    builder
      .addCase(fetchModelComparisons.fulfilled, (state, action: PayloadAction<ModelComparison[]>) => {
        state.comparisons = action.payload;
      });
  }
});

export const {
  fetchModelsStart,
  fetchModelsSuccess,
  fetchModelsFailure,
  fetchModelComparisonsSuccess,
  setCurrentModel
} = modelSlice.actions;

export const fetchModels = createAsyncThunk(
  'models/fetchModels',
  async () => {
    const res = await getModels();
    return res.models;
  }
);

export const fetchModelComparisons = createAsyncThunk(
  'models/fetchModelComparisons',
  async (timeRange: string) => {
    // 根据 timeRange 处理参数
    const days = timeRange === 'day' ? 1 : timeRange === 'week' ? 7 : timeRange === 'month' ? 30 : 90;
    const res = await getModelComparisons(days);
    return res.comparisons;
  }
);


export default modelSlice.reducer;


    